package com.you.concurrent.juc.readwritelock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    static int num = 0;

    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //读写锁

    Lock readLock = readWriteLock.readLock(); //读锁

    Lock writeLock = readWriteLock.writeLock(); //写锁

    public void setValue(int num) {
        try {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            writeLock.lock();
            this.num = num;
            System.out.println("<><>set value is: " + this.num);
        } finally {
            writeLock.unlock();
        }
    }

    public void getValue() {
        try {
            try {
                Thread.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            readLock.lock();
            System.out.println("--------get value is: " + this.num);
        } finally {
            readLock.unlock();
        }
    }

    public static void main(String[] args) {
        //写线程
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        for (int i = 0; i < 5; i++) {
            final int index = i;
            new Thread(() -> {
                readWriteLockDemo.setValue(index + 1);
            }).start();
        }
        //读线程
        for (int i = 0; i < 50; i++) {
            final int index = i;
            new Thread(() -> {
                readWriteLockDemo.getValue();
            }).start();
        }
    }
}
